import axios from "axios"
import { ElMessage } from "element-plus"
import { getToken, removeToken } from "./cookie"
import router from "@/router"

axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8"


const service = axios.create({
    baseURL: '/dev-api',
    timeout: 5000
})

service.interceptors.request.use(
    config => {
        if (getToken()) {
            config.headers["Authorization"] = "Bearer " + getToken()
        }
        return config
    },
    error => {
        console.log(error)
        Promise.reject(error)
    }
)

service.interceptors.response.use(
    res => {
        const code = res.data.code
        const msg = res.data.msg
        if (code === 3001) {
            ElMessage.error(msg)
            removeToken()
            router.push('/oj/login')
            return Promise.reject(new Error(msg))
        }
        if (code != 1000) {
            ElMessage.error(msg)
            return Promise.reject(new Error(msg))
        } else {
            return Promise.resolve(res.data)
        }
    },
    error => {
        const status = error.response.status
        if (status === 500) {
            ElMessage.error('服务器繁忙')
        }
        return Promise.reject(error)
    }
)

export default service